﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using BUS;
using Entity;
using Share;

namespace SLMNG
{
    public partial class M_Payments : BaseForm
    {
        dsCatalogue.InvoiceDetailsDataTable dt = new dsCatalogue.InvoiceDetailsDataTable();
        dsCatalogue.TablesDataTable dtTable;
        bool isPayment;

        #region Constructor and form event

        public M_Payments()
        {
            InitializeComponent();
            isPayment = false;
            this.Load += new EventHandler(Form1_Load);
            GridFormat();
            //btnGetNextNumber.Enabled = false;
            cmbTable.EditValueChanged += cmbTable_EditValueChanged;
            StatusOfForm = FormStatus.Add;
            dtTable = new dsCatalogue.TablesDataTable();
            cmbZone.EditValueChanged += cmbZone_EditValueChanged;
            txtTotalAmount.Properties.DisplayFormat.FormatString = Global.NumberFormatDefault;
            txtTotalAmount.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
        }

        void cmbZone_EditValueChanged(object sender, EventArgs e)
        {
            string code = cmbZone.EditValue.ToString();
            DataRow[] dr = dtTable.Select("ZoneCode = '" + code + "'");
            cmbTable.Properties.DataSource = dr;
        }               

        void Form1_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            string[] arg = new string[] { "ZoneCode" };
            object[] obj = new object[] { DBNull.Value };
            DataSet ds1 = CatalogueBase.GetData(Zone.STORE_SELECT, arg, obj);
            cmbZone.Properties.DataSource = ds1.Tables[0];

            arg = new string[] { "ZoneCode", "TableCode" };
            obj = new object[] { DBNull.Value, DBNull.Value };
            DataTable dtResult = CatalogueBase.GetData(Table.STORE_SELECT, arg, obj).Tables[0];
            dtTable.Clear();
            foreach (DataRow item in dtResult.Rows)
            {
                dtTable.ImportRow(item);
            }
        }

        void cmbTable_EditValueChanged(object sender, EventArgs e)
        {
            txtCode.Text = string.Empty;
            isPayment = false;

            string[] arg = new string[] { "TableCode", "Time" };
            object[] obj = new object[] { cmbTable.EditValue.ToString(), DateTime.Now };
            DataTable dtResult = CatalogueBase.GetData(InvoiceDTO.STORE_SELECT_TABLE_AT_CURRENT_TIME, arg, obj).Tables[0];

            if (dtResult.Rows.Count > 0)
            {
                //btnGetNextNumber.Enabled = false;
                txtCode.Text = dtResult.Rows[0]["InvoiceCode"].ToString();
                dtpDate.EditValue = dtResult.Rows[0]["InvoiceDate"];
                dtpTimeUp.EditValue = dtResult.Rows[0]["TimeUp"];
                txtTotalAmount.Text = dtResult.Rows[0]["TotalAmount"].ToString();

                dt.Clear();
                arg = new string[] { "InvoiceCode" };
                obj = new object[] { dtResult.Rows[0]["InvoiceCode"] };
                DataTable dtTemp = CatalogueBase.GetData(InvoiceDetail.STORE_SELECT_BY_INVOICECODE, arg, obj).Tables[0];
                foreach (DataRow item in dtTemp.Rows)
                {
                    dt.ImportRow(item);
                }
            }
            else
                ClearForm();
        }

        private void GridFormat()
        {
            gridView.DataSource = dt;
            gridView1.Columns["UnitCost"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridView1.Columns["UnitCost"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridView1.Columns["Amount"].DisplayFormat.FormatString = Global.CurrencyFormat;
            gridView1.Columns["Amount"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gridView1.Columns["Quantity"].DisplayFormat.FormatString = Global.FORMAT_NUMBER;
            gridView1.Columns["Quantity"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            txtTotalAmount.Properties.DisplayFormat.FormatString = Global.CurrencyFormat;
            txtTotalAmount.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
        }

        private void btnPayment_Click(object sender, EventArgs e)
        {
            if (!txtCode.Text.Equals(string.Empty) && gridView1.RowCount > 0 && !isPayment)
            {
                if (MessageBox.Show("Bạn muốn thanh toán hóa đơn này ?", this.Text, MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                {
                    string[] arg = new string[] { "InvoiceCode", "TimeOut", "IsPayment" };
                    object[] obj = new object[] { txtCode.Text, dtpTimeOut.EditValue, true };
                    string result = CatalogueBase.SaveData(InvoiceDTO.STORE_UPDATE, arg, obj);
                    if (result.Equals("0"))
                    {
                        isPayment = true;
                        MessageBox.Show(Messages.INVOICE_PAYMENT_SUCCESS, this.Text);
                    }
                    else
                        MessageBox.Show(HandleException.HandleSQLException(result), this.Text);
                }
            }
        }

        #endregion

        #region Overrides Methods

        public override void fncInsert()
        {
            
        }

        public override void fncSave()
        {
            if (string.IsNullOrEmpty(txtCode.Text.Trim()))
            {
                MessageBox.Show(temp.ID_IS_NOT_NULL);
                return;
            }
            else if (gridView1.RowCount <= 0)
            {
                MessageBox.Show("Lưới phải có ít nhất 1 dòng!");
                return;
            }

            DataSet ds = new DataSet();

            decimal totalAmount = 0;

            DataTable dt2 = dt.Copy();
            dt2.TableName = "InvoiceDetail";
            dt2.Columns.Remove("ItemName");
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                decimal amount = Global.decimalParse(dt2.Rows[i]["Amount"]);
                if (amount <= 0)
                {
                    dt2.Rows.RemoveAt(i);
                    i--;
                }
                else
                    totalAmount += amount;
            }

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("InvoiceCode", typeof(string));
            dt1.Columns.Add("InvoiceDate", typeof(DateTime));
            dt1.Columns.Add("TableCode", typeof(string));
            dt1.Columns.Add("EmployeeCode", typeof(string));
            dt1.Columns.Add("CreatedBy", typeof(string));
            dt1.Columns.Add("TimeUp", typeof(DateTime));
            dt1.Columns.Add("TotalAmount", typeof(decimal));

            DataRow dr = dt1.NewRow();
            dr["InvoiceCode"] = txtCode.Text.Trim();
            dr["InvoiceDate"] = DateTime.Now;
            dr["TableCode"] = cmbTable.EditValue.ToString();
            dr["TotalAmount"] = totalAmount;
            dr["CreatedBy"] = Global.UserID;
            dr["EmployeeCode"] = DBNull.Value;
            dr["TimeUp"] = dtpTimeUp.EditValue;
            dt1.Rows.Add(dr);

            ds.Tables.Add(dt1);            
            ds.Tables.Add(dt2);

            string result = string.Empty;
            if (StatusOfForm == FormStatus.Add)
            {
                string[] arg = new string[] { InvoiceDTO.STORE_INSERT, InvoiceDetail.STORE_INSERT };
                result = CatalogueBase.SaveData(arg, ds);
            }
            else if(StatusOfForm == FormStatus.Edit)
            {
                string[] arg = new string[] { InvoiceDTO.STORE_UPDATE, InvoiceDetail.STORE_INSERT };
                result = CatalogueBase.SaveData(arg, ds);
            }

            if (result == "0")
            {
                ClearForm();
                MessageBox.Show(temp.STATUS_INSERT_SUCCESS, this.Text);
            }
            else
                MessageBox.Show(HandleException.HandleSQLException(result), this.Text);
        }

        private void ClearForm()
        {
            txtCode.Text = string.Empty;
            dt.Clear();
            txtTotalAmount.Text = string.Empty;
        }

        public override void fncEdit()
        {
            
        }

        public override void fncDelete()
        {
            
        }

        public override void fncRefresh()
        {
            
        }

        public override void fncPrint()
        {
            string _rptFile = "InvoiceReport.rpt";
            CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
            rpt.Load(Application.StartupPath + "\\Report\\" + _rptFile);
            rpt.SetDataSource(dt as DataTable);

            string timeUp = Global.CombineDateAndTime(dtpDate.EditValue, dtpTimeUp.EditValue).ToString();
            string timeOut = Global.CombineDateAndTime(dtpDate.EditValue, dtpTimeOut.EditValue).ToString();
            rpt.SetParameterValue("InvoiceCode", txtCode.Text);
            rpt.SetParameterValue("TimeUp", timeUp);
            rpt.SetParameterValue("TimeOut", timeOut);
            rpt.SetParameterValue("TableCode", cmbTable.EditValue.ToString());
            rpt.SetParameterValue("PrintNo", "2");
            rpt.SetParameterValue("UserID", Global.UserID);

            MainReport mrpt = new MainReport(rpt);
            mrpt.Show();
           // MessageBox.Show(timeUp);
        }

        #endregion

    }
}
